<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <treeTools :tree-node="comparns" :is-root="true" @addDepartment="addDepts" />
        <el-tree :data="departs" :props="defaultProps" :default-expand-all="true">
          <treeTools slot-scope="{ data }" :tree-node="data" @delDepartment="getDepartments" @addDepartment="addDepts" @editDept="editDept" />
        </el-tree>
      </el-card>
    </div>
    <add-dept ref="addDept" :is-dialog.sync="isDialog" :node-tree="node" @addDetps="getDepartments" />
  </div>
</template>

<script>
import { getDepartment } from '@/api/departments'
import treeTools from '@/views/departments/commpont/tree-tools'
import addDept from '@/views/departments/commpont/add-dept'
export default {
  components: {
    treeTools,
    addDept
  },
  data() {
    return {
      comparns: { },
      departs: [],
      defaultProps: {
        label: 'name' // 表示 从这个属性显示内容
      },
      isDialog: false, // 控制弹层
      node: {}, // 传递给子组件的数据
      loading: false // 加载状态
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() { // 调用接口 获取数据
      this.loading = true
      const res = await getDepartment()
      console.log('进入接口')
      console.log(res)
      this.comparns = { name: res.companyName, manager: '负责人', id: '' }
      const list = this.listGrouping(res.depts, '')
      this.departs = list
      this.loading = false
    },
    listGrouping(list, value) {
      // 1.定义一个数组，用于存放结构化数组
      // 注意：每一次进入此函数的arr代表的含义都不相同
      const arr = []
      list.forEach(item => { // 2.将扁平化数组遍历
        if (item.pid === value) { // 将每一项进行比较，满足条件追加
          const children = this.listGrouping(list, item.id) // 如果满足子集条件，将返回的这一项进行赋值
          if (children.length) item.children = children // 如果没有匹配的，这不需要在item这一项中追加children
          arr.push(item) // 将item追加如数组
        }
      })
      return arr // 返回最终数据---结构化数组
    },
    addDepts(v) { // 将弹层关闭，并将子组件的数据接收
      this.isDialog = true
      this.node = v
    },
    editDept(v) {
      this.isDialog = true // 打开弹层
      this.node = v
      this.$refs.addDept.getDepartDetail(v.id)
    }
  }
}
</script>

<style scode >
.tree-card {
  padding: 30px  140px;
  font-size:14px;
  line-height: 40px;
}
</style>
